package org.nuplay;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import com.illposed.osc.OSCMessage;

public class NuPlayConnector {
	private DatagramSocket client_socket;
	private DatagramPacket packet;
	private Integer channel;

	public NuPlayConnector(InetAddress address, Integer in_channel) {
		this.channel = in_channel;
		try {
			client_socket = new DatagramSocket();
			client_socket.connect(address, 3333);
			packet = new DatagramPacket(new byte[255], 255);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		System.out.println("closed");
		client_socket.close();
		client_socket = null;
	}
	

	public void sendFFT(float values[]) {
		for(int i = 0; i < values.length; i++) {
			packet = new DatagramPacket(new byte[255], 255);
			OSCMessage osc_message = new OSCMessage();
			osc_message.setAddress("/nuplay/channel_" + (this.channel));
			osc_message.addArgument(new String("midi"));
			osc_message.addArgument(new String("control_change"));
			osc_message.addArgument(new Integer(1));
			osc_message.addArgument(new Integer(60 + i));
			osc_message.addArgument(new Integer((int) Math.round(values[i] / 2)));
			osc_message.addArgument(new String(""));
			packet.setData(osc_message.getByteArray());
			try {
				client_socket.send(packet);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
}
